package com.baizhi.controller;/**
 * @Author:luoht
 * @Description：
 * @Date：Create in 20:40 2018/12/24
 */

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @program: SpringCloud
 * @description:
 * @author: luoht
 * @create: 2018-12-24 20:40
 **/
@RestController
@RequestMapping("/hello")
public class HelloController {

    @RequestMapping("/world")
    public String sayHello1(String name){
        RestTemplate restTemplate = new RestTemplate();
        String forObject = restTemplate.getForObject("http://localhost:9090/hello/world?name=" + name, String.class);
        System.out.println(forObject);
        return forObject;
    }

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    //第二种调用方式

    @RequestMapping("/adrien")
    public String sayHello2(String name){
        RestTemplate restTemplate = new RestTemplate();
        //此服务名,得到一台机器的实例，此为客户端的负载均衡(随机策略)
        ServiceInstance serviceInstance = loadBalancerClient.choose("HELLO-SERVICE");
        String host = serviceInstance.getHost();
        int port = serviceInstance.getPort();
        String forObject = restTemplate.getForObject("http://" + host + ":" + port + "/hello/world?name=" + name, String.class);
        System.out.println(forObject);
        return forObject;
    }

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("/daniel")
    public String sayHello3(String name){
        String forObject = restTemplate.getForObject("http://HELLO-SERVICE/hello/world?name=" + name, String.class);
        System.out.println(forObject);
        return forObject;
    }


}
